package model
{
	import controller.MoveEvent;
	
	import flash.events.SyncEvent;
	import flash.net.NetConnection;
	import flash.net.SharedObject;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import red5.as3.net.Connection;
	import red5.as3.net.events.ConnectionEvent;
	
	import view.mediators.BoardMediator;
	
	public class BoardProxy extends Proxy implements IProxy
	{
		public static const NAME:String = "Board Proxy";
		public static const DEFAULT_RED5:String = "rtmp://localhost/test";
		
		private var conn:Connection;
		private var nc:NetConnection;
		private var boardSO:SharedObject;
		private var uri:String;
		
		public function BoardProxy()
		{
			super(NAME);
			conn = new Connection();
			this.uri = BoardProxy.DEFAULT_RED5;
			conn.addEventListener(Connection.SUCCESS, handleSuccessfulConnection);
			conn.addEventListener(Connection.DISCONNECTED, handleDisconnection);
			conn.setURI(this.uri);
			conn.connect();
		}
		
		public function handleSuccessfulConnection(e:ConnectionEvent):void{
			nc = conn.getConnection();
			boardSO = SharedObject.getRemote("boardSO", this.uri, false);
			boardSO.addEventListener(SyncEvent.SYNC, sharedObjectSyncHandler);
			boardSO.client = this;
			boardSO.connect(nc);
		}
		
		public function sharedObjectSyncHandler(e:SyncEvent):void{
			
		}
		
		public function handleDisconnection(e:ConnectionEvent):void{
			sendNotification(BoardFacade.CONNECTION_FAILED);
		}
		
		public function sendMove(x1:Number, y1:Number, x2:Number, y2:Number):void{
			sendNotification(BoardFacade.DEBUG, "" + x1 + " " + y1 + " " + x2 + " " + y2);
			boardSO.send("moveReceived", x1, y1, x2, y2);
		}
		
		public function moveReceived(x1:Number, y1:Number, x2:Number, y2:Number):void{
			sendNotification(BoardMediator.PIECE_MOVED, new MoveEvent(x1,y1,x2,y2));
		}

	}
}